package com.freedom.admin.application.service.cmd;

import com.freedom.admin.application.converter.UserConverter;
import com.freedom.admin.domain.service.UserRoleService;
import com.freedom.admin.domain.service.UserService;
import com.freedom.admin.infrastructure.persistence.pojo.bo.UserBO;
import com.freedom.admin.infrastructure.persistence.pojo.form.UserForm;
import com.freedom.admin.infrastructure.persistence.pojo.form.UserPasswordForm;
import com.freedom.admin.infrastructure.persistence.pojo.form.UserStatusForm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserCmdService {

    private final UserService userService;

    private final UserRoleService userRoleService;

    private final UserConverter userConverter;

    @Transactional(rollbackFor = Exception.class)
    public Boolean addUser(UserForm userForm) {
        UserBO userBO = userConverter.formToBO(userForm);
        Integer userId = userService.save(userBO);

        userRoleService.save(userId, userForm.getRoleIds());

        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyUser(UserForm userForm) {
        UserBO userBO = userConverter.formToBO(userForm);
        userService.modifyById(userBO);

        userRoleService.modifyByIds(userForm.getId(), userForm.getRoleIds());

        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean removeUsers(List<Integer> ids) {
        userService.removeByIds(ids);
        userRoleService.removeByUserIds(ids);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyUserPassword(UserPasswordForm userPasswordForm) {
        UserBO userBO = new UserBO(userPasswordForm.getUserId(), userPasswordForm.getNewPassword());
        userService.modifyUser(userBO);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean modifyUserStatus(UserStatusForm userStatusForm) {
        UserBO userBO = new UserBO(userStatusForm.getUserId(), userStatusForm.getStatus());
        userService.modifyUser(userBO);
        return Boolean.TRUE;
    }
}
